import time

from selenium import webdriver
import re

from finance.selenium_test import getBrowser
import tushare as ts
import pandas as pd

code = 'sh601127'

def getPriceByApi(code):
    import requests  # 参考网址：https://blog.csdn.net/wqy161109/article/details/80052716
    url = 'http://hq.sinajs.cn/list='+code
    res = requests.get(url).text
    print(res)

    # 拆分获取到的字符串
    res_split = res.split(',')
    print(res_split)

    # 提取信息
    open_price = res_split[1]
    pre_close_price = res_split[2]
    now_price = res_split[3]
    high_price = res_split[4]
    low_price = res_split[5]

    print('开盘价为：' + open_price)
    print('昨日收盘价价为：' + pre_close_price)
    print('当前价格为：' + now_price)
    print('最高价为：' + high_price)
    print('最低价为：' + low_price)

def getPriceByPage(code):
    browser = getBrowser()
    browser.get('http://finance.sina.com.cn/realstock/company/'+code+'/nc.shtml')
    data = browser.page_source
    # print(data)
    p_price = '<div id="price" class=".*?">(.*?)</div>'
    price = re.findall(p_price, data)
    print(price)

def tushare():
    pro = ts.pro_api(
        '75fe6c69bb10c996a556a402dde9fdf6e691dfdd2c30ff028ebd5a37')  # 官方文档：https://tushare.pro/document/2?doc_id=36
    # 获取股价数据
    df = pro.daily(ts_code='600519.SH', start_date='20180101', end_date='20201111')

    # 获取财务信息
    df = pro.balancesheet(ts_code='600519.SH', start_date='20190930', end_date='20201231',
                          fields='ts_code, end_date, money_cap, total_assets')
    print(df)

def getTable():
    # 大宗交易
    url = 'http://vip.stock.finance.sina.com.cn/q/go.php/vInvestConsult/kind/dzjy/index.phtml'
    table = pd.read_html(url)[0]  # 核心代码

    # 上市公司资产负债表获取
    url = 'https://money.finance.sina.com.cn/corp/go.php/vFD_BalanceSheet/stockid/600519/ctrl/part/displaytype/4.phtml'
    table = pd.read_html(url)  # 核心代码
    df = table[14]
    df.columns = df.iloc[0]  # 设置表头为原表格的第1行
    df = df[1:]  # 从第2行开始取数据
    df = df.dropna()  # 删除含有空值的行
    print(df)

"""自动投票"""
def vote():
    browser = getBrowser()
    browser.get(r'E:\书籍\Python零基础爬虫入门到精通\4.Selenium进阶\自动投票\vote.html')  # 这个路径需要改一下

    for i in range(10):
        browser.find_element_by_xpath('//*[@id="main"]/tbody/tr[1]/td/input').click()  # 模拟点击某选项
        browser.find_element_by_xpath('//*[@id="main"]/tbody/tr[19]/td/input').click()  # 模拟点击投票按钮
        browser.switch_to.alert.accept()  # 切换到弹出框，并选择接受
        time.sleep(1)

if __name__ == '__main__':
    # getPriceByPage(code)
    # getPriceByApi(code)
    # tushare()
    getTable()
    pass